package com.algorithm.base.backtracking;

import java.util.*;

/**
 * 51. N 皇后
 *
 * @author Amadeus
 * @date 2023/11/10
 */
public class SolveNQueens {

    List<List<String>> result = new ArrayList<>();

    public List<List<String>> solveNQueens(int n) {
        char[][] chessBoard = new char[n][n];
        for (char[] chars : chessBoard) {
            Arrays.fill(chars, '.');
        }
        backTracking(chessBoard, n, 0);
        return result;
    }

    public void backTracking(char[][] chessBoard, int n, int row) {
        if (row == n) {
            result.add(Array2List(chessBoard));
            return;
        }
        //行遍历
        for (int i = 0; i < n; i++) {
            if (isValid(chessBoard, i, row, n)) {
                chessBoard[i][row] = 'Q';
                backTracking(chessBoard, n, row + 1);
                chessBoard[i][row] = '.';
            }
        }
    }

    public List<String> Array2List(char[][] chessboard) {
        List<String> list = new ArrayList<>();
        for (char[] c : chessboard) {
            list.add(String.copyValueOf(c));
        }
        return list;
    }

    private boolean isValid(char[][] chessBoard, int i, int row, int n) {
        for (int j = 0; j < row; j++) {
            if (chessBoard[i][j] == 'Q') {
                return false;
            }
        }
        for (int j = i - 1, k = row - 1; j >= 0 && k >= 0; j--, k--) {
            if (chessBoard[j][k] == 'Q') {
                return false;
            }
        }
        for (int j = i + 1, k = row - 1; j < n && k >= 0; j++, k--) {
            if (chessBoard[j][k] == 'Q') {
                return false;
            }
        }
        return true;
    }

}
